package Twx0429;

import Twx0429.UserService;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;


public class UserListener implements ActionListener{
    JTextField nameIn2;
    JPasswordField pwdIn2;
    UserService userService = new UserService();

    public void actionPerformed(ActionEvent e) {
        String ac = e.getActionCommand();//读取按钮上的文本，放入ac中

        String name = nameIn2.getText();
        String pwd = pwdIn2.getText();

        UserStorage storage = new UserStorage();

        if (ac.equals("登录")){
            int loginCode = userService.login(name,pwd);
            switch (loginCode){
                case 0:
                    JOptionPane.showConfirmDialog(null,"用户已在线");
                    break;
                case 1:
                    JOptionPane.showConfirmDialog(null,"登录成功");
                    storage.changeUsers(name);
                    break;
                case 2:
                    JOptionPane.showConfirmDialog(null,"密码错误");
                    break;
                case 3:
                    JOptionPane.showConfirmDialog(null,"用户未注册");
                    break;
            }
        } else if (ac.equals("注册")) {
            int regCode = userService.register(name,pwd);
            switch (regCode){
                case 0:
                    JOptionPane.showConfirmDialog(null,"该用户已存在");
                    break;
                case 1:
                    JOptionPane.showConfirmDialog(null,"账号为长度大于5，小于12的字母或数字");
                    break;
                case 2:
                    JOptionPane.showConfirmDialog(null,"密码为长度大于6，小于12的字母或数字");
                    break;
                case 3:
                    JOptionPane.showConfirmDialog(null,"注册成功，请前往登录");
                    List<User> data = new ArrayList<User>();
                    data.add(new User(name, pwd, false));
                    storage.saveUsers(data);
                    break;

            }

        }
    }
}
